package com.polaris.live.im.sfs.processor.impl

import com.lxj.xpopup.XPopup
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.dialog.NormalNoticeDialog
import com.polaris.live.im.sfs.COMMAND_NOTICE_POPUP_WINDOW
import com.polaris.live.im.sfs.bean.pusher.PopupWindowMessage
import com.polaris.live.im.sfs.bean.pusher.PusherNoticeMessage
import com.polaris.live.im.sfs.core.bean.DataArgument
import com.polaris.live.im.sfs.processor.AbstractMessageProcessor
import com.polaris.live.resp.event.LiveBannedEvent
import com.polaris.live.ui.live.activity.LiveVideoActivity
import com.polaris.live.ui.live.activity.end.live.LiveEndActivity
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus

/**
 * 通知弹窗
 *
 * @author Created by lucas on 2023/10/19 16:25
 * @since 1.0.0
 */
class NoticeWindowMessageProcessor : AbstractMessageProcessor() {

    override fun shouldProcess(type: Int, command: String): Boolean {
        return command == COMMAND_NOTICE_POPUP_WINDOW
    }

    override suspend fun handle(type: Int, command: String, argument: DataArgument) {
        val data = argument.getData<PusherNoticeMessage>() ?: return
        val message = JsonUtils.fromJson<PopupWindowMessage>(data.content) ?: return

        withContext(CoroutineScopeManager.mainDispatcher) {
            val activity = ViewUtils.getAliveTopActivity()

            if (activity is LiveVideoActivity || activity is LiveEndActivity) {
                EventBus.getDefault().postSticky(LiveBannedEvent(message))
            } else if (activity != null) {
                XPopup.Builder(activity)
                    .apply {
                        if (message.shadow != null) {
                            if (message.shadow.enabled) {
                                hasShadowBg(true)
                            } else {
                                hasShadowBg(false)
                            }
                            if (!message.shadow.clickClose) {
                                dismissOnTouchOutside(false)
                            } else {
                                dismissOnTouchOutside(true)
                            }
                        } else {
                            hasShadowBg(true)
                        }
                    }
                    .isDestroyOnDismiss(true)
                    .asCustom(NormalNoticeDialog(activity, message))
                    .show()
            }
        }
    }
}